#include <REGX52.H>
#include "AT24C02.h"
#include "Delay.h"
#include "DS18B20.h"
#include "dulianjian.h"
#include "I2C.h"
#include "LCD1602.h"
#include "OneWire.h"

unsigned char KeyNum;
float T,TShow; 
char TLow,THigh;	//温度最低和最高阈值


void main()
{	
	THigh=AT24C02_ReadByte(0);
	TLow=AT24C02_ReadByte(1);	//读出上次记录的温度阈值
	if(THigh>125 || TLow<-55 || THigh<=TLow)
	{
		THigh=20;			//如果阈值非法，则设为默认值
		TLow=15;
	}
	LCD_Init();
	LCD_ShowString(2,1,"TH:");
	LCD_ShowString(2,9,"TL:");
	LCD_ShowSignedNum(2,4,THigh,3);
	LCD_ShowSignedNum(2,12,TLow,3);
	
	while(1)
	{
		KeyNum=dulianjian();
		//温度检测
		DS18B20_ConvertT();
		T=DS18B20_ReadT();	//检测温度读出温度并将其赋给T
		if(T<0)
		{
			LCD_ShowString(1,1,"-");
			TShow=-T;	//在不改变T的情况下将T的值显示在LCD
		}
		else
		{
			LCD_ShowString(1,1,"+");
			TShow=T;
			;
		}
		LCD_ShowNum(1,2,TShow,3);
		LCD_ShowString(1,5,".");
		LCD_ShowNum(1,6,(unsigned long)T*100%100,3);	//LCD无法显示小数，将小数转换后单独显示
		//阈值判断及调节	
		if(KeyNum)
		{
			if(KeyNum==1)
			{
				THigh++;
				if(THigh>125){THigh=125;}
			}
			if(KeyNum==2)
			{
				THigh--;
				if(THigh<=TLow){THigh++;}
			}
			if(KeyNum==3)
			{
				TLow++;
				if(TLow>=THigh){TLow--;}
			}
			if(KeyNum==4)
			{
				TLow--;
				if(TLow<-55){TLow=-55;}
			}
		}
		LCD_ShowSignedNum(2,4,THigh,3);
		LCD_ShowSignedNum(2,12,TLow,3);
		AT24C02_WriteByte(0,THigh);
		Delay(5);
		AT24C02_WriteByte(1,TLow);	//写入当前温度阈值，写入需要延时5ms
		Delay(5);
		if(T>THigh)
		{
			LCD_ShowString(1,13,"OV:H");
		}
		else if(T<TLow)
		{
			LCD_ShowString(1,13,"OV:L");
		}
		else
		{
			LCD_ShowString(1,13,"    ");
		}
	}
}